//
//  TaskManagerMainVC.m
//  LogisticsSupplier
//
//  Created by 吕晶 on 2021/3/19.
//  Copyright © 2021 吕晶. All rights reserved.
//

#import "TaskManagerMainVC.h"
#import "TaskManagerNavBar.h"
#import "TaskManagerSearchModel.h"
#import "TaskManagerScreenView.h"
#import "TaskManagerListVC.h"
#import "TaskManagerListModel.h"
#import "TaskManagerListCell.h"
#import "BoHuiReasonAlertView.h"
#import "TaskManagerDetailVC.h"
#import "TaskGuiJiVC.h"

@interface TaskManagerMainVC ()<ZJScrollPageViewDelegate,UITableViewDelegate,UITableViewDataSource> {
    int page;
    NSInteger type;
    BOOL isShowScreenView;//是否显示筛选框
    BOOL isJiHuaListHasAppear;//计划列表是否出现过。（第一次出现过时刷新分栏控件，避免计划第一页跟未完成第一页重复的bug）
    BOOL isWeiFinishListHasAppear;//未完成列表是否出现过。（第一次出现过时刷新分栏控件，避免计划第一页跟未完成第一页重复的bug）
}

@property (nonatomic, strong) TaskManagerNavBar *navBar;
@property (nonatomic, strong) UIView *searchView;
@property (nonatomic, strong) UITextField *searchField;
@property (nonatomic, strong) ZJSegmentStyle *menuStyle;//菜单栏
@property (nonatomic, strong) NSArray<NSString *> *titles;
@property (nonatomic, strong) ZJScrollPageView *scrollPageView;
@property (nonatomic, strong) UIView *scrollPageBGView;
@property (nonatomic, strong) ZJSegmentStyle *menuStyle2;//菜单栏
@property (nonatomic, strong) NSArray<NSString *> *titles2;
@property (nonatomic, strong) ZJScrollPageView *scrollPageView2;
@property (nonatomic, strong) UIView *scrollPageBGView2;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray <TaskManagerListModel *>*dataArray;
@property (nonatomic, strong) TaskManagerSearchModel *searchModel;
@property (nonatomic, strong) TaskManagerScreenView *screenView;

@end

@implementation TaskManagerMainVC

-(TaskManagerScreenView *)screenView {
    if (!_screenView) {
        _screenView = [TaskManagerScreenView new];
        __weak_self;
        _screenView.dismissBlock = ^{
            [weakself shaiXuanClick];
        };
        _screenView.finishBlock = ^(TaskManagerSearchModel * _Nonnull model) {
            [weakself shaiXuanClick];
            weakself.searchModel = model;
            __strong_self;
            if (strongSelf->type != 1 && strongSelf->type != 11) {
                [strongSelf refreshList:nil];
            }else {
                [[NSNotificationCenter defaultCenter] postNotificationName:ReceiptDeliveryRefreshTaskManagerList object:nil userInfo:[strongSelf.searchModel mj_keyValues]];
            }
        };
    }
    return _screenView;
}

-(TaskManagerSearchModel *)searchModel {
    if (!_searchModel) {
        _searchModel = [TaskManagerSearchModel new];
    }
    return _searchModel;
}

-(NSMutableArray<TaskManagerListModel *> *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.searchView.nim_bottom, ScreenW, ScreenH - BottomHeight - NaviHeight - 54) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = Color_backgroundColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"img_occupy"
             titleStr:@""
            detailStr:@""];
        __weak_self;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            __strong_self;
            strongSelf->page = 1;
            [strongSelf requestForList];
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            __strong_self;
            strongSelf->page++;
            [strongSelf requestForList];
        }];
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
    }
    return _tableView;
}

-(TaskManagerNavBar *)navBar {
    if (!_navBar) {
        _navBar = [[TaskManagerNavBar alloc] initWithFrame:CGRectMake(0, 0, ScreenW, NaviHeight)];
        _navBar.titleStr = @"我的任务";
        __weak_self;
        _navBar.backBlock = ^{
            [weakself.rt_navigationController popViewControllerAnimated:YES];
        };
        _navBar.changeBlock = ^(NSInteger type) {
            [weakself changeView:type];
        };
    }
    return _navBar;
}

- (void)changeView:(NSInteger)status {
    if (type != status) {
        type = status;
        if (status == 1) {
            self.scrollPageBGView.hidden = NO;
            self.scrollPageView.hidden = NO;
            self.scrollPageBGView2.hidden = YES;
            self.scrollPageView2.hidden = YES;
            self.tableView.hidden = YES;
            if (!isWeiFinishListHasAppear) {
                [self.scrollPageView reloadWithNewTitles:self.titles];
                isWeiFinishListHasAppear = YES;
            }
        }else if (status == 11) {
            self.scrollPageBGView2.hidden = NO;
            self.scrollPageView2.hidden = NO;
            self.scrollPageBGView.hidden = YES;
            self.scrollPageView.hidden = YES;
            self.tableView.hidden = YES;
            if (!isJiHuaListHasAppear) {
                [self.scrollPageView2 reloadWithNewTitles:self.titles2];
                isJiHuaListHasAppear = YES;
            }
        }else {
            self.scrollPageBGView.hidden = YES;
            self.scrollPageView.hidden = YES;
            self.scrollPageBGView2.hidden = YES;
            self.scrollPageView2.hidden = YES;
            self.tableView.hidden = NO;
            [self refreshList:nil];
        }
    }
}

-(UIView *)searchView {
    if (!_searchView) {
        _searchView = [[UIView alloc] initWithFrame:CGRectMake(0, self.navBar.nim_bottom, ScreenW, 54)];
        _searchView.backgroundColor = HexColor(0xffffff);
        
        UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(10, 10, self.searchView.nim_width - 75, 34)];
        bgView.backgroundColor = HexColor(0xF2F2F5);
        bgView.layer.masksToBounds = YES;
        bgView.layer.cornerRadius = 4;
        [_searchView addSubview:bgView];
        
        UIButton *searchBtn = [[UIButton alloc] initWithFrame:CGRectMake(bgView.nim_width - 10 - 30 - 10, 7, 30, 20)];
        [searchBtn setTitle:@"搜索" forState:0];
        [searchBtn setTitleColor:Color_ThemeColor forState:0];
        searchBtn.titleLabel.font = BoldFontOfSize(14);
        [searchBtn addTarget:self action:@selector(searchClick) forControlEvents:UIControlEventTouchUpInside];
        [bgView addSubview:searchBtn];
        
        self.searchField = [[UITextField alloc] initWithFrame:CGRectMake(10, 7, searchBtn.nim_left - 10 - 10, 20)];
        self.searchField.placeholder = @"任务来源";
        self.searchField.font = [UIFont systemFontOfSize:14];
        [bgView addSubview:self.searchField];
        
        UIButton *shaiXuanBtn = [[UIButton alloc] initWithFrame:CGRectMake(bgView.nim_right, bgView.nim_top, 60, bgView.nim_height)];
        [shaiXuanBtn setTitle:@"筛选" forState:0];
        [shaiXuanBtn setTitleColor:HexColor(0x2B2C44) forState:0];
        shaiXuanBtn.titleLabel.font = BoldFontOfSize(14);
        [shaiXuanBtn setImage:[UIImage imageNamed:@"icon_my_takeorder_shaixuan"] forState:0];
        [shaiXuanBtn addTarget:self action:@selector(shaiXuanClick) forControlEvents:UIControlEventTouchUpInside];
        [_searchView addSubview:shaiXuanBtn];
    }
    return _searchView;
}

//搜索点击
- (void)searchClick {
    self.searchModel.t_name = self.searchField.text.length ? self.searchField.text : @"";
    if (type != 1 && type != 11) {
        [self refreshList:nil];
    }else {
        [[NSNotificationCenter defaultCenter] postNotificationName:ReceiptDeliveryRefreshTaskManagerList object:nil userInfo:[self.searchModel mj_keyValues]];
    }
}

//筛选点击
- (void)shaiXuanClick {
    if (isShowScreenView) {
        isShowScreenView = NO;
        [self.screenView disMissView];
    }else {
        isShowScreenView = YES;
        self.screenView.model = self.searchModel;
        [self.screenView showInView:MAIN_WINDOW];
    }
}

-(ZJScrollPageView *)scrollPageView {
    if (!_scrollPageView) {
        _scrollPageView = [[ZJScrollPageView alloc] initWithFrame:CGRectMake(0, self.searchView.nim_bottom, ScreenW, ScreenH - self.searchView.nim_bottom) segmentStyle:self.menuStyle titles:self.titles parentViewController:self delegate:self];
    }
    return _scrollPageView;
}

-(UIView *)scrollPageBGView {
    if (!_scrollPageBGView) {
        _scrollPageBGView = [[UIView alloc] initWithFrame:CGRectMake(0, self.searchView.nim_bottom, ScreenW, 40)];
        _scrollPageBGView.backgroundColor = [UIColor whiteColor];
    }
    return _scrollPageBGView;
}

-(ZJSegmentStyle *)menuStyle {
    if (!_menuStyle) {
        _menuStyle = [ZJSegmentStyle new];
        _menuStyle.autoAdjustTitlesWidth = YES;
        _menuStyle.showLine = YES;//显示下划线
        _menuStyle.scrollTitle = YES;//设置标题栏可以滚动
        _menuStyle.segmentViewBounces = YES;//设置滚动标题栏有弹性
        _menuStyle.scaleTitle = YES;//设置选中标题缩放
        _menuStyle.scrollContentView = YES;//内容可以滑动
        _menuStyle.normalTitleColor = HexColor(0x9C9DB3);
        _menuStyle.selectedTitleColor = Color_ThemeColor;
        _menuStyle.scrollLineColor = Color_ThemeColor;
        _menuStyle.scrollLineWidth = 12;
        _menuStyle.segmentHeight = 40;
        _menuStyle.titleBigScale = 1.1;
        _menuStyle.titleFont = [UIFont systemFontOfSize:14];
    }
    return _menuStyle;
}

-(NSArray<NSString *> *)titles {
    if (!_titles) {
        _titles = @[@"全部",@"未受理",@"已受理",@"提货出发",@"提货到达",@"送货出发",@"送货到达",@"签收"];
    }
    return _titles;
}

-(ZJScrollPageView *)scrollPageView2 {
    if (!_scrollPageView2) {
        _scrollPageView2 = [[ZJScrollPageView alloc] initWithFrame:CGRectMake(0, self.searchView.nim_bottom, ScreenW, ScreenH - self.searchView.nim_bottom) segmentStyle:self.menuStyle2 titles:self.titles2 parentViewController:self delegate:self];
    }
    return _scrollPageView2;
}

-(UIView *)scrollPageBGView2 {
    if (!_scrollPageBGView2) {
        _scrollPageBGView2 = [[UIView alloc] initWithFrame:CGRectMake(0, self.searchView.nim_bottom, ScreenW, 40)];
        _scrollPageBGView2.backgroundColor = [UIColor whiteColor];
    }
    return _scrollPageBGView2;
}

-(ZJSegmentStyle *)menuStyle2 {
    if (!_menuStyle2) {
        _menuStyle2 = [ZJSegmentStyle new];
        _menuStyle2.autoAdjustTitlesWidth = YES;
        _menuStyle2.showLine = YES;//显示下划线
        _menuStyle2.scrollTitle = YES;//设置标题栏可以滚动
        _menuStyle2.segmentViewBounces = YES;//设置滚动标题栏有弹性
        _menuStyle2.scaleTitle = YES;//设置选中标题缩放
        _menuStyle2.scrollContentView = YES;//内容可以滑动
        _menuStyle2.normalTitleColor = HexColor(0x9C9DB3);
        _menuStyle2.selectedTitleColor = Color_ThemeColor;
        _menuStyle2.scrollLineColor = Color_ThemeColor;
        _menuStyle2.scrollLineWidth = 12;
        _menuStyle2.segmentHeight = 40;
        _menuStyle2.titleBigScale = 1.1;
        _menuStyle2.titleFont = [UIFont systemFontOfSize:14];
    }
    return _menuStyle2;
}

-(NSArray<NSString *> *)titles2 {
    if (!_titles2) {
        _titles2 = @[@"未受理",@"已受理"];
    }
    return _titles2;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    page = 1;
    type = 1;
    isShowScreenView = NO;
    isJiHuaListHasAppear = NO;
    isWeiFinishListHasAppear = NO;
    self.navigationController.navigationBar.hidden = YES;
    [self.view addSubview:self.navBar];
    [self.view addSubview:self.searchView];
    [self.view addSubview:self.scrollPageBGView];
    [self.view addSubview:self.scrollPageView];
    [self.view addSubview:self.scrollPageBGView2];
    self.scrollPageBGView2.hidden = YES;
    [self.view addSubview:self.scrollPageView2];
    self.scrollPageView2.hidden = YES;
    [self.view addSubview:self.tableView];
    self.tableView.hidden = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshList:) name:ReceiptDeliveryRefreshTaskManagerList object:nil];
    if (self.isPlan) {
        [self changeView:11];
        self.navBar.s_type = 11;
        if (self.selectIdx) {
            [self.scrollPageView2 setSelectedIndex:self.selectIdx animated:YES];
        }
    }else {
        if (self.selectIdx) {
            [self.scrollPageView setSelectedIndex:self.selectIdx animated:YES];
        }
        if (self.isBoHui) {
            [self changeView:3];
            self.navBar.s_type = 3;
        }
    }
}

- (void)refreshList:(NSNotification *)noti {
    if (noti) {
        TaskManagerSearchModel *model = [TaskManagerSearchModel mj_objectWithKeyValues:noti.userInfo];
        if (model) {
            self.searchModel = model;
        }
    }
    page = 1;
    [self requestForList];
}

- (void)requestForList {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if (type) {
        [dic setObject:@(type) forKey:@"status"];
    }
    [dic setObject:@(page) forKey:@"page"];
    if (self.searchModel.the_num.length) {
        [dic setObject:self.searchModel.the_num forKey:@"the_num"];
    }
    if (self.searchModel.s_city.length) {
        [dic setObject:self.searchModel.s_city forKey:@"s_city"];
    }
    if (self.searchModel.r_city.length) {
        [dic setObject:self.searchModel.r_city forKey:@"r_city"];
    }
    if (self.searchModel.t_name.length) {
        [dic setObject:self.searchModel.t_name forKey:@"t_name"];
    }
    if (self.searchModel.car_require_name.length) {
        [dic setObject:@(self.searchModel.car_require) forKey:@"car_require"];
    }
    if (self.searchModel.pnum_min.length) {
        [dic setObject:self.searchModel.pnum_min forKey:@"pnum_min"];
    }
    if (self.searchModel.pnum_max.length) {
        [dic setObject:self.searchModel.pnum_max forKey:@"pnum_max"];
    }
    if (self.searchModel.weight_min.length) {
        [dic setObject:self.searchModel.weight_min forKey:@"weight_min"];
    }
    if (self.searchModel.weight_max.length) {
        [dic setObject:self.searchModel.weight_max forKey:@"weight_max"];
    }
    if (self.searchModel.volume_min.length) {
        [dic setObject:self.searchModel.volume_min forKey:@"volume_min"];
    }
    if (self.searchModel.volume_max.length) {
        [dic setObject:self.searchModel.volume_max forKey:@"volume_max"];
    }
    if (self.searchModel.strat_time.length) {
        [dic setObject:self.searchModel.strat_time forKey:@"strat_time"];
    }
    if (self.searchModel.end_time.length) {
        [dic setObject:self.searchModel.end_time forKey:@"end_time"];
    }
    [HttpRequest PostWithApi:LogisticsSupplierTaskManagerList params:dic progress:^(NSProgress * _Nonnull progress) {

    } success:^(NSURLSessionDataTask * _Nonnull operation, id  _Nonnull responseObject, BOOL code, NSInteger errorCode) {
        if (code) {
            if (self->page == 1) {
                [self.dataArray removeAllObjects];
                self.dataArray = [TaskManagerListModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
            }else {
                NSArray *array = [TaskManagerListModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
                [self.dataArray addObjectsFromArray:array];
            }
            BOOL has_more = [responseObject[@"has_more"] boolValue];
            if (has_more) {
                self.tableView.mj_footer.hidden = NO;
            }else {
                self.tableView.mj_footer.hidden = YES;
            }
            [self.tableView reloadData];
        }
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    } fail:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

- (NSInteger)numberOfChildViewControllers {
    if (type == 1) {
        return self.titles.count;
    }else if (type == 11) {
        return self.titles2.count;
    }
    return 0;
}

- (UIViewController<ZJScrollPageViewChildVcDelegate> *)childViewController:(UIViewController<ZJScrollPageViewChildVcDelegate> *)reuseViewController forIndex:(NSInteger)index {
    if (type == 1) {
        TaskManagerListVC<ZJScrollPageViewChildVcDelegate> * childVC = (TaskManagerListVC *)reuseViewController;
        TaskManagerListVC *vc = [TaskManagerListVC new];
        vc.searchModel = self.searchModel;
        if (index == 0) {
            //@"全部"
            vc.status = 0;
        }else if (index == 1) {
            //@"未受理"
            vc.status = 1;
        }else if (index == 2) {
            //@"已受理"
            vc.status = 2;
        }else if (index == 3) {
            //@"提货出发"
            vc.status = 4;
        }else if (index == 4) {
            //@"提货到达"
            vc.status = 5;
        }else if (index == 5) {
            //@"送货出发"
            vc.status = 6;
        }else if (index == 6) {
            //@"送货到达"
            vc.status = 7;
        }else if (index == 7) {
            //@"签收"
            vc.status = 8;
        }
        childVC = vc;
        return childVC;
    }else {
        TaskManagerListVC<ZJScrollPageViewChildVcDelegate> * childVC = (TaskManagerListVC *)reuseViewController;
        TaskManagerListVC *vc = [TaskManagerListVC new];
        vc.searchModel = self.searchModel;
        if (index == 0) {
            //@"未受理"
            vc.status = 11;
            vc.jh_status = 1;
        }else if (index == 1) {
            //@"已受理"
            vc.status = 11;
            vc.jh_status = 2;
        }
        childVC = vc;
        return childVC;
    }
}

//子控制器实现完整生命周期
- (BOOL)shouldAutomaticallyForwardAppearanceMethods {
    return NO;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TaskManagerListCell *cell = [TaskManagerListCell TaskManagerListCellWithTableView:tableView];
    TaskManagerListModel *model = self.dataArray[indexPath.section];
    cell.model = model;
    __weak_self;
    cell.boHuiReasonBlock = ^{
        BoHuiReasonAlertView *alert = [BoHuiReasonAlertView new];
        alert.timeStr = model.create_time;
        alert.reasonStr = model.reject_remarks;
        [alert showInView:weakself.view];
    };
    cell.guiJiBlock = ^{
        TaskGuiJiVC *vc = [TaskGuiJiVC new];
        vc.sta_id = model.Id;
        [weakself.rt_navigationController pushViewController:vc animated:YES];
    };
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    TaskManagerListCell *cell = [TaskManagerListCell TaskManagerListCellWithTableView:tableView];
    TaskManagerListModel *model = self.dataArray[indexPath.section];
    cell.model = model;
    return cell.height;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    TaskManagerListModel *model = self.dataArray[indexPath.section];
    TaskManagerDetailVC *vc = [TaskManagerDetailVC new];
    vc.sta_id = model.Id;
    if ([model.status isEqualToString:@"3"]) {
        vc.isBoHui = YES;
    }
    [self.rt_navigationController pushViewController:vc animated:YES];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
        view.backgroundColor = Color_backgroundColor;
        return view;
    }
    return [UIView new];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 10;
    }
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, 10)];
    view.backgroundColor = Color_backgroundColor;
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
